#include "analog_clock.h"
#include <math.h>

void drawAnalogClock(Panel &panel, uint16_t posX, uint16_t posY, uint16_t w, uint16_t h, uint8_t hour, uint8_t minute, uint8_t second) {
    // compute center and radius inside bounding box
    uint16_t cx = posX + w / 2;
    uint16_t cy = posY + h / 2;
    uint16_t radius = (w < h ? w : h) / 2;
    if (radius > 2) radius -= 2; // small margin

    // clear the clock area
    if (w > 0 && h > 0) {
        panel.fillRect(posX, posY, posX + w - 1, posY + h - 1, 0, 0, 0);
    }

    // draw outer circle
    panel.drawCircle(cx, cy, radius, 255, 255, 0);

    // draw hour ticks
    for (int i = 0; i < 12; i++) {
        float angle = (i * 30.0f) * M_PI / 180.0f; // degrees to radians
        int16_t sx = cx + (int16_t)((radius - 4) * cos(angle));
        int16_t sy = cy + (int16_t)((radius - 4) * sin(angle));
        int16_t ex = cx + (int16_t)(radius * cos(angle));
        int16_t ey = cy + (int16_t)(radius * sin(angle));
        panel.drawLine(sx, sy, ex, ey, 255, 255, 0);
    }

    // compute angles for hands (0 at 12 o'clock, increasing clockwise)
    float hourAngle = ((hour % 12) + minute / 60.0f) * 30.0f * M_PI / 180.0f;
    float minuteAngle = minute * 6.0f * M_PI / 180.0f;
    float secondAngle = second * 6.0f * M_PI / 180.0f;

    // draw hour hand
    int16_t hx = cx + (int16_t)((radius * 0.5f) * sin(hourAngle));
    int16_t hy = cy - (int16_t)((radius * 0.5f) * cos(hourAngle));
    panel.drawLine(cx, cy, hx, hy, 255, 0, 0);

    // draw minute hand
    int16_t mx = cx + (int16_t)((radius * 0.7f) * sin(minuteAngle));
    int16_t my = cy - (int16_t)((radius * 0.7f) * cos(minuteAngle));
    panel.drawLine(cx, cy, mx, my, 0, 255, 0);

    // draw second hand
    int16_t sx = cx + (int16_t)((radius * 0.9f) * sin(secondAngle));
    int16_t sy = cy - (int16_t)((radius * 0.9f) * cos(secondAngle));
    panel.drawLine(cx, cy, sx, sy, 0, 0, 255);
}
